import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 全局样式
import './styles/index.scss'

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(ElementPlus)
app.use(router)
app.use(store)

// 初始化用户状态和权限路由
if (localStorage.getItem('token') && localStorage.getItem('userInfo')) {
  // 已登录状态，初始化权限路由
  store.dispatch('user/initUserState')
} else {
  // 未登录状态，只预先加载路由结构但不应用
  store.dispatch('permission/generateRoutes', null, { root: true })
}

// 错误处理
app.config.errorHandler = (err, vm, info) => {
  console.error('Vue Error:', err)
  console.error('Error Info:', info)
}

app.mount('#app')
